#include "SendImgThread.h"
#include <QBuffer>
#include <QDebug>

extern MsgQueue queue_send;

//消费线程
void SendImgThread::run() {
    qDebug() << "start sending picture thread: " << QThread::currentThreadId();
    m_isCanRun = true;
    for(;;)
    {
        queue_lock.lock(); //加锁

        while(imgqueue.size() == 0)
        {
            //qDebug() << this << QThread::currentThreadId();
            bool f = queue_waitCond.wait(&queue_lock, 5);
			if (f == false) //timeout
			{
				QMutexLocker locker(&m_lock);
				if (m_isCanRun == false)
				{
                    queue_lock.unlock();
					qDebug() << "stop sending picture thread: " << QThread::currentThreadId();
					return;
				}
			}
        }

        queue_send.push_back(imgqueue.front());
        imgqueue.pop_front();
        queue_lock.unlock();//解锁
        queue_waitCond.wakeOne(); //唤醒添加线程

    }
}

//添加线程
void SendImgThread::pushToQueue(QImage img) {
    //压缩
    QByteArray byte;
    QBuffer buf(&byte);
    buf.open(QIODevice::WriteOnly);
    img.save(&buf, "JPEG");

    queue_lock.lock();
    while(imgqueue.size() > QUEUE_MAXSIZE)
    {
        queue_waitCond.wait(&queue_lock);
    }
    imgqueue.push_back(MessageHelper::makeMediaMessage(byte, MSG::Type::VIDEO));
    queue_lock.unlock();
    queue_waitCond.wakeOne();
}

void SendImgThread::ImageCapture(QImage img) {
    pushToQueue(img);
}

void SendImgThread::clearImgQueue() {
    qDebug() << "清空视频队列";
    QMutexLocker locker(&queue_lock);
    while (!imgqueue.empty()) {
        imgqueue.pop_front();
    }
    
}

void SendImgThread::stopImmediately() {
    QMutexLocker locker(&m_lock);
    m_isCanRun = false;
}